from gm.api import *

from gm.model.history import HistoryApi
historyapi = HistoryApi()

import talib
import numpy as np
import matplotlib.pyplot as plt
set_token("2f6fc0b33f43707de870abf5b0c2f9bade9204f2")

import time 
start = time.time()

import pymysql
from sqlalchemy import create_engine
DB_STRING = 'mysql+pymysql://root:kirin@localhost:3306/stock?charset=utf8'
engine = create_engine(DB_STRING)

import pandas as pd

sql = ''' select ts_code,name,industry from gm_market_3113; '''
# read_sql_query的两个参数: sql语句， 数据库连接
df = pd.read_sql_query(sql, engine)
#获取行业名称列表
industry_list=df.drop_duplicates(subset=['industry'],keep='first',inplace=False)['industry'].to_list()
print(industry_list)
grouped = df.groupby('industry')
#获取 行业名称:股票代码列表 字典
dict_by_industry = {industry_list[i]:grouped.get_group(industry_list[i])['ts_code'].to_list() for i in range(len(industry_list))}
#银行列表 = dict_by_industry[industry_list[0]]
import datetime
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# start_day=now-datetime.timedelta(100) #9日交易日(含休市)数据拟合,不能跳过休市日
plt.rcParams['font.sans-serif'] = ['KaiTi']
plt.rcParams['axes.unicode_minus'] = False

class tlb:
    def __init__(self,symbol):
        self.symbol = symbol
        self.name = df.loc[df['ts_code'] == symbol, 'name'].values[0]

    def cur(self):
        current(symbols=self.symbol, fields='price')

    def ma(self,frequency='1d',timeperiod=20,count=180):

        gm_market=pd.DataFrame()
        gm_market=gm_market.append(historyapi.get_history_n_bars(self.symbol,frequency=frequency, count=count, end_time=now, fields='close,eob', skip_suspended=True, \
                fill_missing='Last', adjust=ADJUST_NONE, adjust_end_time='', df=True), ignore_index=True)
        close = np.asarray(gm_market['close'].values)
        eob=[i.strftime('%Y%m%d-%H:%M') for i in np.asarray(gm_market['eob'])]
        ma3= talib.MA(close,timeperiod = timeperiod)
        plt.figure() #更新画布，没有这句，每次调用，plt的对象会重叠
        plt.plot(eob,ma3,'r',close,'b--')
        plt.xticks(range(1,len(eob),int(len(eob)/25)),rotation=45)
        plt.title(self.name)
        plt.show()

    def bbands(self,frequency='1d',timeperiod=20,count=180):
        gm_market=pd.DataFrame()
        gm_market=gm_market.append(historyapi.get_history_n_bars(self.symbol,frequency=frequency, count=count, end_time=now, fields='close,eob', skip_suspended=True, \
                fill_missing='Last', adjust=ADJUST_NONE, adjust_end_time='', df=True), ignore_index=True)
        close = np.asarray(gm_market['close'].values)
        eob=[i.strftime('%Y%m%d-%H:%M') for i in np.asarray(gm_market['eob'])]
        upperband,middleband,lowerband=talib.BBANDS(close, timeperiod=timeperiod,nbdevup=2.0, nbdevdn=2.0,matype=talib.MA_Type.EMA)
        for i in range(count):
            if  close[i] > upperband[i]:
                print(eob[i],"卖出")
            elif close[i] < lowerband[i]:
                print(eob[i],'买入')
        plt.figure() #更新画布，没有这句，每次调用，plt的对象会重叠
        plt.plot(eob,upperband,'r',close,'b--',lowerband,'g')
        plt.xticks(range(1,len(eob),int(len(eob)/25)),rotation=45)
        plt.title(self.name)
        plt.show()

symbol=dict_by_industry[industry_list[0]][0]
tb = tlb(symbol)
# tb.ma(frequency='60s')
tb.bbands(frequency='60s')
print("执行时间 {} 秒".format(round(time.time() - start, 2)))